package com.butterfly.rest.resource.restlet.status;

import com.butterfly.rest.resource.restlet.exception.AdXException;
import org.restlet.data.Status;
import org.restlet.ext.jackson.JacksonRepresentation;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

@Component
public class ErrorUtil {
    public JacksonRepresentation<AdxError> generateErrorMessage(Status status) {
        AdxError error = new AdxError();
        error.setErrorCode(status.getCode());
        error.setErrorMessage(status.getDescription());
        return new JacksonRepresentation<AdxError>(error);
    }

    public Status getStatus(Throwable throwable) {
        int code = HttpStatus.INTERNAL_SERVER_ERROR.ordinal();
        String reasonPhrase = HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();
        String errorDescription = "Adx Internal error";
        if (throwable instanceof AdXException) {
            AdXException exception = (AdXException) throwable;
            code = exception.getErrorCode().getHttpStatus().ordinal();
            errorDescription = exception.getErrorCode().getErrorDescription();
            reasonPhrase = exception.getErrorCode().getHttpStatus().getReasonPhrase();
        }
        return new Status(code, reasonPhrase, errorDescription, null);
    }
}
